/**
 * Element.getBoundingClientRect()方法返回元素的四个角相对于视口的位置，可以准确定位到元素的位置
 * getComputedStyle 返回元素的css属性
 */

export default {
  getPosition: function (el) {
    return {
      x: el.getBoundingClientRect().x,
      y: el.getBoundingClientRect().y,
      toRight: document.body.clientWidth - el.getBoundingClientRect().right, // 距离屏幕右边距离
      toBottom: document.body.clientHeight - el.getBoundingClientRect().bottom // 距离屏幕下边距离
    }
  },
  getEleArg (ele, property, type) { // 获取元素css属性
    const args = this.getComputedStyle(ele)
    if (property) {
      return type === 'int' ? parseInt(args[property]) : args[property]
    } else {
      return args
    }
  },
  getComputedStyle (element) {
    return getComputedStyle(element)
  },
  getScrollParent (element) { // 获取有滚动的父元素
    if (!element) {
      return document.body;
    }
    switch (element.nodeName) {
      case 'HTML':
      case 'BODY':
        return element.ownerDocument.body;
      case '#document':
        return element.body;
    }
    const { overflow, overflowX, overflowY } = this.getComputedStyle(element)
    if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) {
      return element
    }
    return this.getScrollParent(this.getParentNode(element))
  },
  getParentNode (element) {
    if (element.nodeName === 'HTML') {
      return element
    }
    return element.parentNode || element.host
  },
  removeEle (child) {
    const parent = child.parentNode
    parent.removeChild(child)
  },
  appendEle (parent, child) {
    parent.appendChild(child)
  },
  transEleToBody (child) {
    const innerChild = child
    this.removeEle(child)
    this.appendEle(document.body, innerChild)
  },
  getOffsetPosition (elem) { // 获取元素真正的top和left
    /**
     * documentElement: 根节点
     * clientTop: 边框高度
     * clientLeft: 边框宽度
     * pageYOffset: 当前页面相对于窗口显示区左上角的 Y 位置
     * pageXOffset: 当前页面相对于窗口显示区左上角的 X 位置
     * 公式逻辑：当前元素距离窗口显示区左上角的距离 + 当前页面相对于窗口显示区左上角的距离
     */
    if (!elem) {
      return {
        left: 0,
        top: 0
      }
    }
    var top = 0, left = 0
    if ('getBoundingClientRect' in document.documentElement) {
      var box = elem.getBoundingClientRect(),
      doc = elem.ownerDocument,
      body = doc.body,
      docElem = doc.documentElement,
      clientTop = docElem.clientTop || body.clientTop || 0,
      clientLeft = docElem.clientLeft || body.clientLeft || 0,
      top = box.top + (window.pageYOffset || docElem && docElem.scrollTop  || body.scrollTop) - clientTop,
      left = box.left + (window.pageXOffset || docElem && docElem.scrollLeft || body.scrollLeft) - clientLeft
    } else {
      do {
        top += elem.offsetTop || 0
        left += elem.offsetLeft || 0
        elem = elem.offsetParent
      } while (elem)
    }
    return {left: left, top: top}
  }
}